import {useCallback, useEffect, useState} from 'react'
import Tabs from "../../components/tabs";
import useCountdown from "../../hooks/useCountdown";
import InfiniteScroll from "../../components/infiniteScoll";
import moreImg from "./images/more.png"
import advancedImg from "./images/advanced.png"
import empty from "./images/empty.png"
import emptyAvatar from "./images/avatar-empty.png"
import cupImg from "./images/cup.png"
import './index.scss'
import Modal from "../../components/modal";

const data = Array(4).fill({})
const target = new Date("2023-06-06 10:10:10")
const TAB_DATA = [
  {
    name: 'User list',
    tab: 0,
    apiKey: '',
  },
  {
    name: 'Daily tasks',
    tab: 1,
    apiKey: '',
  },
  {
    name: 'Daily list',
    tab: 2,
    apiKey: '',
  },
]
const STAGE_DATA = [
  {
    name: 'Stage 1',
    subName: '4/25',
    tab: 0,
    apiKey: '',
    msg: 'N into 100',
    timeStart: '2022-4-25 00:00:00',
    timeEnd: '2022-4-25 23:59:59',
  },
  {
    name: 'Stage 2',
    subName: '4/26',
    tab: 1,
    apiKey: '',
    msg: '100 into 50',
    timeStart: '2022-4-26 00:00:00',
    timeEnd: '2022-4-26 23:59:59',
  },
  {
    name: 'Stage 3',
    subName: '4/27~4/28',
    tab: 2,
    apiKey: '',
    msg: '',
    timeStart: '2022-4-27 00:00:00',
    timeEnd: '2022-4-28 23:59:59',
  },
  {
    name: 'Invitational',
    subName: '4/29~4/30',
    tab: 3,
    apiKey: '',
    msg: 'Entry requirements',
    timeStart: '2022-4-29 00:00:00',
    timeEnd: '2022-4-30 23:59:59',
  },
]
const DAILY_DATA = [
  {
    name: 'Day1 4/25',
    tab: 0,
    apiKey: '2022-04-25',
    timeStart: '2022-4-25 00:00:00',
    timeEnd: '2022-4-25 23:59:59',
  },
  {
    name: 'Day2 4/26',
    tab: 1,
    apiKey: '2022-04-26',
    timeStart: '2022-4-26 00:00:00',
    timeEnd: '2022-4-26 23:59:59',
  },
  {
    name: 'Day3 4/27',
    tab: 2,
    apiKey: '2022-04-27',
    timeStart: '2022-4-27 00:00:00',
    timeEnd: '2022-4-27 23:59:59',
  },
  {
    name: 'Day4 4/28',
    tab: 3,
    apiKey: '2022-04-28',
    timeStart: '2022-4-28 00:00:00',
    timeEnd: '2022-4-28 23:59:59',
  },
  {
    name: 'Day5 4/29',
    tab: 4,
    apiKey: '2022-04-29',
    timeStart: '2022-4-29 00:00:00',
    timeEnd: '2022-4-29 23:59:59',
  },
  {
    name: 'Day6 4/30',
    tab: 5,
    apiKey: '2022-04-30',
    timeStart: '2022-4-30 00:00:00',
    timeEnd: '2022-4-30 23:59:59',
  },
]
const DAILY_REWARDS = [
  {
    name: 'TOP1',
    value: 50000,
    icon: 'diamond'
  },
  {
    name: 'TOP2',
    value: 40000,
    icon: 'diamond'
  },
  {
    name: 'TOP3',
    value: 30000,
    icon: 'diamond'
  },
  {
    name: 'TOP4',
    value: 20000,
    icon: 'diamond'
  },
  {
    name: 'TOP5',
    value: 10000,
    icon: 'diamond'
  }
]
const SLICE = 6

function GameKingRank() {
  const [activeTab, setActiveTab] = useState(TAB_DATA[0])
  const [activeSubTab, setActiveSubTab] = useState(STAGE_DATA[0])
  const [activeDailySubTab, setActiveDailySubTab] = useState(DAILY_DATA[0])
  const [, {days, hours, minutes, seconds}] = useCountdown({
    targetDate: target,
    onEnd: () => {
      console.log("countdown is over")
    }
  })
  const [showMore, setShowMore] = useState(true)
  const [sliceIndex, setSliceIndex] = useState(SLICE)
  const [isOver, setIsOver] = useState(false)
  const [isStart, setIsStart] = useState(true)
  const [awardVisible, setAwardVisible] = useState(false)
  const [advancedIsVisible, setAdvancedIsVisible] = useState(false)
  const [isUserList, setIsUserList] = useState(false)
  const [isDailyList, setIsDailyList] = useState(false)
  const [isDailyTask, setIsDailyTask] = useState(false)
  const [isStage4, setIsStage4] = useState(false)

  useEffect(() => {
    setActiveSubTab(STAGE_DATA[0])
    setActiveDailySubTab(DAILY_DATA[0])
    setIsUserList(activeTab.tab === 0)
    setIsDailyTask(activeTab.tab === 1)
    setIsDailyList(activeTab.tab === 2)
  }, [activeTab.tab])

  useEffect(() => {
    const isStage4 = activeTab.tab === 0 && activeSubTab.tab === 3
    setIsStage4(isStage4)

    if (activeTab.tab === 1) {
      setIsStart(true)
      setIsOver(false)
      return
    }

    let nowTime = Date.now()
    let {timeStart, timeEnd} = activeSubTab
    if (activeTab.tab === 2) {
      timeStart = activeDailySubTab.timeStart
      timeEnd = activeDailySubTab.timeEnd
    }

    const startTime = new Date(timeStart).getTime()
    const endTime = new Date(timeEnd).getTime()
    setIsStart(nowTime >= startTime)
    setIsOver(nowTime >= endTime)
    setAdvancedIsVisible(nowTime >= endTime)

  }, [activeTab.tab, activeSubTab.tab])

  const handleChange = d => {
    setActiveTab(d)
    setSliceIndex(SLICE)
  }

  const handleSubTabChange = d => {
    setActiveSubTab(d)
  }

  const openRule = () => {
    window.location.href = "/layout/game-king-rank/rule"
  }
  const openRecord = () => {
    window.location.href = "/layout/game-king-rank/record"
  }

  const drawAward = () => {
    setAwardVisible(true)
  }

  const loadData = () => {
    setTimeout(() => {
      setSliceIndex(d => d + SLICE)
    }, 1000)
  }

  useEffect(() => {
    setShowMore(sliceIndex < data.length)
  }, [sliceIndex, data.length])

  const renderItem = useCallback((d, i) => {
    const isReceived = false
    if (isDailyTask) {
      return (
        <div className="task-item">
          <div className={`task-box ${isReceived && 'done'}`}/>
          <div className="task-progress">
            <p className="text">Flow reaches:</p>
            {renderProgress(100, 30)}
          </div>
          <button className="receive-btn" disabled={isReceived} onClick={drawAward}>
            Receive
          </button>
        </div>
      )
    }
    let showEmptySeat = i <= 2 && isStage4
    let flag
    if (isUserList && activeSubTab.tab === 0) {
      flag = i <= 100
    } else if (isUserList && activeSubTab.tab === 1) {
      flag = i <= 50
    } else {
      flag = false
    }
    const showAdvanced = advancedIsVisible && flag
    if (d.fake && i > 2 && isStage4) {
      return null
    }

    return (
      <div className="normal-item">
        {showAdvanced && (<img src={advancedImg} alt="" className="advanced"/>)}
        <div className="rank-num">
          {i + 1}
        </div>
        <div className="avatar">
          <img src={showEmptySeat ? (d.url || emptyAvatar) : d.url} alt=""/>
        </div>
        <div className="user-info">
          <p className="name">{showEmptySeat ? (d.name || 'Waiting for an empty seat') : d.name}</p>
        </div>
        <div className="num">
          999w
        </div>
      </div>
    )
  }, [activeTab.tab, activeSubTab.tab, isStage4, isDailyTask, advancedIsVisible, isUserList])

  const renderLoading = useCallback(() => (
    <div className="more">
      <img src={moreImg} alt=""/>
      <span>more</span>
    </div>
  ), [])

  const renderFooter = useCallback(() => {
    return (
      (
        <li className="item item-self">
          <div className="normal-item">
            {/*<img src={advancedImg} alt="" className="advanced"/>*/}
            <div className="rank-num">
              999+
            </div>
            <div className="avatar">
              <img src="" alt=""/>
            </div>
            <div className="user-info">
              <p className="name">
                name
              </p>
            </div>
            <div className="num">
              999w
            </div>
          </div>
        </li>
      )
    )
  }, [activeTab.tab])

  const renderEmpty = useCallback((text) => (
    <div className="empty">
      <img src={empty} alt=""/>
      {!!text && <p className="rank-info">{text} Has not started</p>}
      {!text && <p>No data</p>}
    </div>
  ), [])

  const renderProgress = useCallback((target, current) => (
    <div className="progress">
      <div className="inner" style={{width: `${current * 100 / target}%`}}/>
      {current}/{target}Juta
    </div>
  ), [])

  const renderRewardList = useCallback(() => (
    <ul className="reward-list">
      {DAILY_REWARDS.map(d => (<li key={d.name} className="reward-list-item">
        <span>{d.name}</span>
        <span className={`icon ${d.icon}`}>{d.value}</span>
      </li>))}
    </ul>
  ), [])

  return (
    <div className={`GameKingRank`}>
      <button className="record-btn" onClick={openRecord}>Reward record</button>
      <button className="rule-btn" onClick={openRule}>Aturan</button>

      <p className="time-msg">2022/04/25-2022/04/310</p>

      <Tabs activeKey={activeTab.tab} data={TAB_DATA} onChange={handleChange} className="parent-tabs"/>
      <main>

        {
          !isDailyTask && (
            <div className="stag-wrap">
              <Tabs
                activeKey={isDailyList ? activeDailySubTab.tab : activeSubTab.tab}
                key={activeTab.tab}
                data={isDailyList ? DAILY_DATA : STAGE_DATA}
                onChange={handleSubTabChange}
                className="stage-tabs"
                renderItem={d => (
                  <div>
                    <p className="name">{d.name}</p>
                    <p>{d.subName}</p>
                  </div>
                )}
                style={{
                  transform: `translateX(${-10 * activeSubTab.tab}%)`
                }}
              />
            </div>
          )
        }

        {!!activeSubTab.msg && isUserList && <p className="rank-info">{activeSubTab.msg}</p>}
        {isDailyList && <p className="rank-info daily-list-msg">Daily top 5 will get the following rewards</p>}
        {isOver && <p className="rank-over">Over</p>}

        {!isOver && !isDailyList && !isStage4 && isStart &&
        <div className="countdown">
          {days > 0 && <span className="day">{days}day</span>}
          <span className="time">{hours}</span><span className="dot">:</span>
          <span className="time">{minutes}</span><span className="dot">:</span>
          <span className="time">{seconds}</span>
        </div>
        }

        {isStage4 && (
          <div className="my-progress">
            {renderProgress(100, 30)}
            <button className="done-btn" disabled/>
            <p className="info">04/25～04/28 Accumulated points reach 10 million to participate</p>
          </div>
        )}

        {isDailyList && renderRewardList()}

        {isStart ? (
          (data.length < 1 && !isStage4) ?
            renderEmpty()
            : (
              <InfiniteScroll
                className={`rank-list rank-list-${activeTab.tab}`}
                data={isStage4 ? [...data, ...(Array(3).fill({fake: true}))] : data.slice(0, sliceIndex)}
                renderItem={renderItem}
                itemClassName={"item item-rank"}
                loadData={loadData}
                more={showMore}
                renderLoading={renderLoading}
                renderFooter={renderFooter}
              />
            )) : renderEmpty(isStage4 ? activeSubTab.name : (activeSubTab.msg || activeSubTab.name))
        }
      </main>
      <div className="bg-bottom"/>

      <Modal
        className="award-modal"
        visible={awardVisible}
        closable={false}
        onClose={setAwardVisible.bind(null, false)}
      >
        <h3 className="title">Congratulations</h3>
        <ul className="award-images" style={{justifyContent: 'space-around'}}>
          {/*<ul className="award-images" style={{justifyContent: 'center'}}>*/}
          <li>
            <div className="gift-img"><img src={cupImg} alt=""/></div>
            <p className="gift-name">gift name</p>
          </li>
          <li>
            <div className="gift-img"><img src={cupImg} alt=""/></div>
            <p className="gift-name">gift name</p>
          </li>

        </ul>
        <button onClick={setAwardVisible.bind(null, false)}>Confirm</button>
      </Modal>
    </div>
  )
}

export default GameKingRank
